package com.eascs.admin.o2o.o2ozx.serviceimpl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.eascs.admin.common.utils.IdCard;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.o2ozx.dao.O2oZxDao;
import com.eascs.admin.o2o.zx.entity.O2oLoanUserEntityZx;
import com.eascs.admin.o2o.zx.entity.O2oZxEntity;
import com.eascs.admin.o2o.zx.entity.O2oZxSulpmentEntity;
import com.eascs.admin.o2o.zx.entity.O2oZxSulpmentRecordLogEntity;
import com.eascs.admin.o2o.zx.service.IO2oZxService;
import com.eascs.admin.o2o.zx.vo.O2oZxVo;
import com.eascs.app.dao.PageResult;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.common.custnew.entity.CustomerEntity;
import com.eascs.crm.common.custnew.service.CustomerService;
import com.eascs.crm.common.vo.ModelResult;
import com.eascs.crm.loanstart.form.CustomerBasicInfoForm;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sequence.SequenceEntity;
import com.eascs.workflow.common.service.sequence.SequenceService;

@Service
public class O2oZxServiceImpl implements IO2oZxService{
	
	@Reference
	CustomerService customerService;
	
	@Autowired
	O2oZxDao o2oZxDao;
	
	@Autowired
	private O2oLoanapplyService o2oloanapplyService;
	
	@Reference
	private SequenceService sequenceService;

	@Override
	public int add(O2oZxEntity arg0) {
		// TODO Auto-generated method stub
		return o2oZxDao.insert(arg0);
	}

	@Override
	public O2oZxEntity getEntityById(String id) {
		
		return o2oZxDao.getById(O2oZxEntity.class, id);
	}

	@Override
	public O2oZxEntity getEntityByLoanApplyNo(String arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public PageResult<Object[]> queryEntitys(O2oZxEntity arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int update(O2oZxEntity arg0) {
		
		return o2oZxDao.updateById(arg0);
	}
	
	public PageResult<Object[]>  findByPage(O2oZxVo o2oZxVo){
		
		return o2oZxDao.findByPage(o2oZxVo);
	}
	
	
	public Map<String, String> saveOrupdateCustomerBasicInfo(CustomerBasicInfoForm cbiForm) {
		// 存放验证信息
		Map<String, String> map = new HashMap<>();
		String returnFlag = "success";
		map.put("returnFlag", returnFlag);

		// 客户基本信息
		CustomerEntity basicInfo = new CustomerEntity();

		// 后台验证
		// 1.验证客户身份证
		if (cbiForm != null && cbiForm.getIdType().equals("IDC")) {
			boolean flag1 = IdCard.isIDCard(cbiForm.getIdNumber());
			if (flag1 == false) {
				returnFlag = "客户身份证输入有误";
				map.put("returnFlag", returnFlag);
				return map;
			}
		}
		// 客户标示信息：通过证件号码，证件类型，查出客户信息及其扩展信息是否存在，来确定后面是修改逻辑还是新增逻辑
		String hisCustomerId = cbiForm.getCustomerId();
		String customerId = null;
		customerId = customerService.isCustomerExists(cbiForm.getIdNumber(), cbiForm.getIdType());

		// 对比逻辑：确认客户是否属于重复添加
		int flag = compareIdCard(hisCustomerId, customerId);
		if (flag == 1) {
			returnFlag = "客户证件号码已存在，不能重复添加";
			map.put("returnFlag", returnFlag);
			return map;
		}
		User user = UserHolder.getUser();
		// 客户信息
		if (StringUtil.isNotBlank(hisCustomerId)) {

			basicInfo = customerService.queryCustomerEntityByCustomerId(hisCustomerId);
			if(cbiForm.getMaritalStatus() != 2){
				basicInfo.setSpouse(null);
				basicInfo.setMateId(null);
			}
			if (user != null) {
				basicInfo.setModifier(user.getCname());
				basicInfo.setModifyId(user.getNo());
			}

		} else {
			if (user != null) {
				basicInfo.setCreator(user.getCname());
				basicInfo.setModifier(user.getCname());
				basicInfo.setCreateId(user.getNo());
				basicInfo.setModifyId(user.getNo());
			}
		}

		// 赋值客户信息
		basicInfo.setCustomerFamilyName(cbiForm.getCustomerFamilyName());
		basicInfo.setCustomerGivenName(cbiForm.getCustomerGivenName());
		basicInfo.setIdNumber(cbiForm.getIdNumber());
		basicInfo.setIdType(cbiForm.getIdType());
		basicInfo.setMaritalStatus(cbiForm.getMaritalStatus());
		basicInfo.setMobileNumber(cbiForm.getMobileNumber());
		basicInfo.setCustomerName(cbiForm.getCustomerFamilyName() + cbiForm.getCustomerGivenName());
		basicInfo.setLicenseExpirationDate(DateUtils.formateStandDate(cbiForm.getLicenseExpirationDate()));
		basicInfo.setCustomerNamePinyin(cbiForm.getCustomerNamePinyin());

		// 修改客户信息
		if (StringUtil.isBlank(hisCustomerId)) {
			basicInfo.setCreateDate(new Date());
			basicInfo.setModifyDate(new Date());
			ModelResult<CustomerEntity> model = customerService.addCustomer(basicInfo);
			if (model.isSuccess()) {
				hisCustomerId = model.getModel().getCustomerId();
			}
		} else {
			basicInfo.setModifyDate(new Date());
			customerService.updateCustomer(basicInfo);

		}

		map.put("customerId", hisCustomerId);
		return map;
	}
	
	private int compareIdCard(String hisCustomerId, String customerId ) {
		// 新增客户信息的时候，客户证件号码重复
		if (StringUtil.isBlank(hisCustomerId) && StringUtil.isNotBlank(customerId)) {
			return 1;
		}
		
		// 修改客户信息的时候，客户证件号码改成了另一个已存在的号码
		if (StringUtil.isNotBlank(hisCustomerId) && StringUtil.isNotBlank(customerId)
				&& !hisCustomerId.equals(customerId)) {
			return 1;
		}
		
		return 0;
	}

	@Override
	public PageResult<Object[]> queryFqZxbg(String loanapplyNo) {
	
		return o2oZxDao.queryFqZxbg(loanapplyNo);
	}
	/**
	 * zx 生成贷款编号
	 * 
	 * @param code zx
	 * @param type
	 * @return
	 */
	public String buildCode(String code) {
		String bill = StringUtils.getFourBitYearMonth(new Date());
		String prefix = code + "-" + bill;
		String flag = sequenceService.getSeq(SequenceEntity.O2O_LOAN_NO, 5, prefix);
		if (flag == null) {
			throw new RuntimeException();
		}
		return flag;
	}
	
	
	/**
	 * 新增终端贷 无配偶关系
	 * 
	 * @param loanEntity
	 * @param loanUserEntity
	 * @return
	 */
	@Transactional(transactionManager = "o2oTransactionManager")
	public void saveEntityById(O2oZxEntity o2oZxEntity, O2oLoanUserEntityZx loanUserEntityZx) {
		o2oZxDao.insert(o2oZxEntity);
		loanUserEntityZx.setZxNo(o2oZxEntity.getId());
		o2oZxDao.insert(loanUserEntityZx);
		//return loanDao.insert(loanUserEntity);
	}
	
	@Transactional(transactionManager = "o2oTransactionManager")
	public String saveNewEntityById(O2oZxEntity o2oZxEntity, O2oLoanUserEntityZx loanUserEntityZx) {
		o2oZxDao.insert(o2oZxEntity);
		loanUserEntityZx.setZxNo(o2oZxEntity.getId());
		o2oZxDao.insert(loanUserEntityZx);
		return o2oZxEntity.getId();
	}
	
	/**
	 * 查询附件列表
	 */
	public void queryDatalist(String id) { // 默认下载
		queryDatalist(id,"false");
	}
	
	/**
	 * 查询附件列表,附件是否能下载
	 */
	public void queryDatalistIsReadOnly(String id, String datalistReadonly) {
		queryDatalist(id, datalistReadonly);
	}
	
	/**
	 * 查询附件列表
	 */
	public void queryDatalist(String id,String readonly) { // readonly 是否支持下载 true 不下载
		PageResult<Object[]> pageResult = o2oloanapplyService.findO2oDataListEntityById(id);
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[0];
		if("false".equals(readonly)){
			titleButtons = new Button[] { null, ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		}
		PaginationInfo datalistInfo = new PaginationInfo(pageResult, titles, "/loanUser/loanudpate");
		datalistInfo.setTitleButtons(titleButtons);
		datalistInfo.setBuildPagingNavigation(false);
		datalistInfo.setFirstRenderColumnIndex(1);
		datalistInfo.setBuildRowNumber(true);
		ViewContext.put("datalistInfo", datalistInfo);
	}
	
	/**
	 * 补充征信附件信息
	 */
	public void supplementFile(String loanapplyNo, String readonly) { // readonly 是否支持下载  true 不下载
		List<O2oZxSulpmentEntity> entities = queryListO2oZxSulpmentEntity(loanapplyNo);
		String id = "";
		if (null != entities && entities.size() > 0) {
			for (O2oZxSulpmentEntity entity : entities) {
				id += "'" + entity.getZxNo() + "',";
			}
			id = id.substring(0, id.length() - 1);
		}
		if (StringUtil.isBlank(id)) {
			id = "''";
		}
		PageResult<Object[]> pageResult = o2oloanapplyService.supplementFile(id);
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[0];
		if ("false".equals(readonly)) {
			titleButtons = new Button[] { null, ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		}
		PaginationInfo datalistInfo = new PaginationInfo(pageResult, titles);
		datalistInfo.setTitleButtons(titleButtons);
		datalistInfo.setBuildPagingNavigation(false);
		datalistInfo.setFirstRenderColumnIndex(1);
		datalistInfo.setBuildRowNumber(true);
		ViewContext.put("datalistInfo", datalistInfo);
	}
	
	/**@Description:
	 *               <p>
	 *               夫妻双方历史征信报告
	 *               </p>
	 * @author LMX
	 * @date 2018年1月23日 下午4:00:59
	 * @version V1.0
	 * @param loanapplyNo
	 * @param loanId
	 * @param readonly
	 */
	public void queryHistoryfqZx(String loanapplyNo, String loanId, String readonly) {
		PageResult<Object[]> paymentsResult = o2oZxDao.queryHistoryfqZx(loanapplyNo,loanId);
		String[] paymentstitles = { "报告类型", "文件名", "提交人", "提交时间", "更新时间" };
		PaginationInfo paginationInfo = new PaginationInfo(paymentsResult, paymentstitles);
		SelectDataOption[] selectDataOptions = { new SelectDataOption("ZX_TYPE"), null, null, null, null };
		Button[] titleButtons = new Button[0];
		if("false".equals(readonly)){
			titleButtons = new Button[] { null, ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		}
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("paginationInfo", paginationInfo);
	}
	
	/**@Description:
	 *               <p>
	 *               企业历史征信报告
	 *               </p>
	 * @author LMX
	 * @date 2018年1月24日 上午9:49:46
	 * @version V1.0
	 * @param loanapplyNo
	 * @param loanId
	 * @param readonly
	 */
	public void queryHistoryQyZx(String loanapplyNo, String loanId, String readonly) {
		PageResult<Object[]> paymentsResult = o2oZxDao.queryHistoryQyZx(loanapplyNo,loanId);
		String[] paymentstitles = { "文件名", "提交人", "提交时间", "更新时间" };
		PaginationInfo paginationInfo = new PaginationInfo(paymentsResult, paymentstitles);
		SelectDataOption[] selectDataOptions = { null, null, null, null };
		Button[] titleButtons = new Button[0];
		if("false".equals(readonly)){
			titleButtons = new Button[] { ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		}
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("paginationInfo", paginationInfo);
	}

	
	/**
	 * @Title: bcIsSelectedByOther
	 * @Description: 校验该
	 * @author 张庆奇
	 * @param loanapplyNo
	 * @return
	 * @return boolean
	 * @throws
	 * @date 2018年1月11日 上午9:40:59
	 */
	public boolean bcIsSelectedByOther(String loanapplyNo,String zx_no){
		boolean flag=false;
		String sql="SELECT count(1) FROM o2o_loan_user u LEFT JOIN o2o_zx zx ON u.zx_no = zx.id WHERE u.zx_no = ? AND u.loanapply_no <> ? AND zx.zx_bank = 'BC'  " ;
		int num=o2oZxDao.findInteger(sql, zx_no,loanapplyNo);
		if(num>0){
			flag=true;
		}
		return flag;
	}
	
	/**
	 * @Title: bcIsSelectedByCustomerType
	 * @Description: 关联的中行征信报告是否符合客户类型
	 * @author 张庆奇
	 * @param loanapplyNo
	 * @param zx_no
	 * @param zxType
	 * @return
	 * @return boolean
	 * @throws
	 * @date 2018年1月11日 上午10:57:56
	 */
	public boolean bcIsSelectedByCustomerType(String loanapplyNo,String zx_no,String zxType){
		boolean flag=false;
		String sql="SELECT count(1) FROM o2o_loan_user u LEFT JOIN o2o_zx zx ON u.zx_no = zx.id WHERE u.zx_no = ? AND u.loanapply_no = ? AND zx.zx_bank = 'BC' AND zx.zx_type =?" ;
		Integer num=o2oZxDao.findInteger(sql, zx_no,loanapplyNo,zxType);
		if(num<=0){
			flag=true;
		}
		return flag;
	}

	/**
	 * @Title: bcIsSelectedByCustomerType
	 * @Description: 一个自然月内在同一家银行是否查询过个人征信报告
	 */
	public boolean isMothSelectedZX(String document_no,String bank){
		boolean flag=false;
		String sql="select count(*) from o2o_zx oz LEFT JOIN  o2o_loan_user_zx oluz ON oluz.zx_no=oz.id "
				+ " where oz.zx_status='CLO' and oluz.zx_date is not null and date_format(oluz.zx_date,'%Y-%m') = date_format(NOW(),'%Y-%m') "
				+ "and oz.is_del = 'N' and oz.zx_bank <> 'BC'  and oluz.document_no=? and oz.zx_bank = ?" ;
		Integer num=o2oZxDao.findInteger(sql, document_no,bank);
		if(num>0){
			flag=true;
		}
		return flag;
	}

	@Override
	public int insert(O2oZxSulpmentEntity entity) {
		return o2oZxDao.insert(entity);
	}

	@Override
	public int update(O2oZxSulpmentEntity entity) {
		return o2oZxDao.updateById(entity);
	}

	@Override
	public O2oZxSulpmentEntity getZxEntityById(String id) {
		String sql = "select * from o2o_zx_supplement where is_delete='N' and id=?";
		return o2oZxDao.findEntity(sql, O2oZxSulpmentEntity.class, id);
	}
	
	public O2oZxSulpmentEntity getZxEntityByZxId(String zxNo) {
		String sql = "select * from o2o_zx_supplement where is_delete='N' and zx_no=?";
		return o2oZxDao.findEntity(sql, O2oZxSulpmentEntity.class, zxNo);
	}

	public PageResult<Object[]> queryFqZxbgNew(String loanapplyNo) {
		return o2oZxDao.queryFqZxbgNew(loanapplyNo);
	}

	public List<O2oZxSulpmentEntity> queryListO2oZxSulpmentEntity(String loanapplyNo){
		String sql =  "select * from o2o_zx_supplement where is_delete='N' and loanapply_no=?";
		return o2oZxDao.findEntitys(sql, O2oZxSulpmentEntity.class, loanapplyNo);
	}

	@Override
	public int insert(O2oZxSulpmentRecordLogEntity entity) {
		return o2oZxDao.insert(entity);
	}

	@Override
	public int update(O2oZxSulpmentRecordLogEntity entity) {
		return o2oZxDao.updateById(entity);
	}

	@Override
	public O2oZxSulpmentRecordLogEntity getZxEntityLogById(String id) {
		return o2oZxDao.getById(O2oZxSulpmentRecordLogEntity.class, id);
	}

}
